import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { RegisterService } from '../../service/register.service';
import { SingupParams } from '../../../../../model';
import { RegisterFormData } from '../../model/form.data';

const passwordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const newPassword = control.get('newPassword');
  const confirmPassword = control.get('confirmPassword');
  return newPassword && confirmPassword && newPassword.value !== confirmPassword.value ? { 'passwordError': true } : null;
};

@Component({
  selector: 'app-register-body-password',
  templateUrl: './register-body-password.component.html',
  styleUrls: ['./register-body-password.component.scss']
})
export class RegisterBodyPasswordComponent implements OnInit {

  _account: RegisterFormData; // 不是名字的意思，是账号的意思，懒得改

  @Input()
  set account(_account: RegisterFormData) {
    this._account = _account;
    if (this._account) {
      this.getAuthCodeLable();
    }

  }

  get account() {
    return this._account;
  }

  @Output()
  accountEvent = new EventEmitter<{
    type: 1 | 2,
    msg: string,
  }>();

  emailOrPhone: number;
  passwordForm: FormGroup;
  authCodeLable = '发送验证码';
  timmer: any;

  constructor(
    private router: Router,
    private fb: FormBuilder,
    private registerService: RegisterService,
    private message: NzMessageService,
  ) {
    this.newConstructor();
  }

  getAuthCodeLable() {
    if (this.authCodeLable === '发送验证码') {
      this.registerService.sendCodeForSignUp(this.getSendCodeForSignUpData()).subscribe(res => {
        if (res.status === 0) {
          this.message.info('验证码已经发送');
          let num = 60;
          this.timmer = setInterval(() => {
            this.authCodeLable = '重新发送(' + num + ')';
            num--;
          }, 1000);
          setTimeout(() => {
            clearInterval(this.timmer);
            this.authCodeLable = '发送验证码';
          }, 60 * 1000);
        } else {
          this.accountEvent.next({
            type: 2,
            msg: res.message
          });
          if (this.timmer) {
            clearInterval(this.timmer);
          }
          this.authCodeLable = '发送验证码';
        }
      });
    }
  }

  signup() {
    const param: SingupParams = {
      pwd: this.passwordForm.get('newPassword').value,
      verifyCode: this.passwordForm.get('authCode').value
    };
    if (this.account.type === 1) {
      param.email = this.account.email;
    } else if (this.account.type === 2) {
      param.mobile = this.account.regionNumber + '-' + this.account.phone;
    }
    this.registerService.singup(param).subscribe(res => {
      if (res.status === 0) {
        this.router.navigateByUrl('pages/register/success');
      } else {
      
        this.registerService.error(res);
      }
    }, error => this.registerService.error(error));
  }

  changeAccount() {
    this.accountEvent.next({
      type: 1,
      msg: 'error'
    });
    if (this.timmer) {
      clearInterval(this.timmer);
    }
    this.authCodeLable = '发送验证码';
  }

  ngOnInit() {
  }

  private newConstructor() {

    this.initPasswordForm();
  }


  private initPasswordForm() {
    this.passwordForm = this.fb.group({
      authCode: [null, [Validators.required]],
      // tslint:disable-next-line:max-line-length
      newPassword: [null, [Validators.required, Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,24}'), passwordValidator]], // 其实是密码的意思，懒得改
      confirmPassword: [null, [Validators.required, Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,24}'), passwordValidator]],
    });

    this.passwordForm.setValidators(passwordValidator);
  }

  private getSendCodeForSignUpData(): { email: string } | { mobile: string } {
    if (this.account.type === 1) {
      return {
        email: this.account.email
      };
    } else if (this.account.type === 2) {
      return {
        mobile: this.account.regionNumber + '-' + this.account.phone
      };
    }
  }

}

